package com.qbw.app.module.vehicle.popwindow;

import android.content.Context;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lib.util.ScreenUtil;
import com.qbw.actionmanager.ActionManager;
import com.qbw.app.R;
import com.qbw.app.databinding.VehiclePopwindowSelectBinding;
import com.qbw.app.model.Vehicle;
import com.qbw.app.module.vehicle.holder.VehicleSelectVehicleItemHolder;
import com.qbw.core.base.BaseAction;
import com.qbw.core.base.BaseAdapter;
import com.qbw.core.base.BasePopupWindow;

/**
 * @author QBW
 * @date 2019-09-01
 */
public class VehicleSelectPopWindow extends BasePopupWindow<VehiclePopwindowSelectBinding> implements VehicleSelectVehicleItemHolder.Listener {

    private Vehicle.VehicleList mVehicleList;

    public VehicleSelectPopWindow(Context context, Vehicle.VehicleList vehicleList) {
        super(context,
              R.layout.vehicle_popwindow_select,
              ScreenUtil.dp2px(context, 117),
              calculateHeight(context, vehicleList));
        mVehicleList = vehicleList;
        initData();
    }

    @Override
    protected void init() {
        super.init();

    }

    private static int calculateHeight(Context context, Vehicle.VehicleList vehicleList) {
        int size = vehicleList.size();
        if (size <= 10) {
            return ViewGroup.LayoutParams.WRAP_CONTENT;
        } else {
            return (int) (10 * context.getResources()
                                      .getDimension(R.dimen.vehicle_select_item_height));
        }
    }

    private void initData() {
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(mContext));
        InnerAdapter adapter = new InnerAdapter(mContext, this);
        adapter.addChild(mVehicleList.getList());
        mBinding.rcv.setAdapter(adapter);
    }

    @Override
    public void onSelectVehicle(Vehicle vehicle) {
        dismiss();
        Vehicle currentVehicle = mVehicleList.getIndexVehicle();
        if (currentVehicle != null && currentVehicle != vehicle) {
            currentVehicle.setIndex(false);
            vehicle.setIndex(true);
            ActionManager.getInstance().triggerAction(new SelectedVehicleChangedAction(vehicle));
        }
    }


    private static class InnerAdapter extends BaseAdapter {

        public InnerAdapter(Context context, Object listener) {
            super(context, listener);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new VehicleSelectVehicleItemHolder(mContext, parent, mListener);
        }

        @Override
        public int getItemViewType(Object t) {
            return 1;
        }
    }

    public static class SelectedVehicleChangedAction extends BaseAction<Vehicle> {

        public SelectedVehicleChangedAction(Vehicle vehicle) {
            super(vehicle);
        }
    }
}
